<?php

namespace app\http\middleware;

use app\models\{Admin as model, Systemlog};

use think\Db;

class Admin
{
    public function handle($request, \Closure $next)
    {
        $id = session('admin_id');
        $admin = (new model())->where('id', $id)->find();
        $url = $request->baseUrl();
        if (!$admin && $url != '/index/login') {
            return redirect('index/login');
        }
        if ($admin && $url == '/') {
            return redirect('main/index');
        }
        $auth = config('auth.admin');
        $admin['role'] = array_filter(explode(',', $admin['role'] ?? '')) ?? [];
        if (!in_array($url, $admin['role']) && !in_array($url, $auth) && $admin['is_default'] == 0) {
            if (request()->isAjax()) {
                return json(['code' => 1, 'msg' => '您没有该操作权限']);
                die;
            } else {
                return view('/main/500');;
            }
        }

        // dump(unserialize(preg_replace_callback('#s:(\d+):"(.*?)";#s', function ($match) {
        //     return 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
        // }, $string)));

        $request->admin = $admin;
        if ($request->isAjax() && request()->controller(true) != 'base' && request()->method() != 'GET') {
            $array = [
                'module'        => 'admin',
                'controller'    => request()->controller(true),
                'action'        => request()->action(true),
                'params'        => serialize(request()->param()),
                'method'        => request()->method(),
                'url'           => request()->baseUrl(),
                'ip'            => request()->ip(),
                'name'          => $admin['username'] ?? '',
            ];
            if (empty($array['name'])) {
                $array['name'] = 'admin';
            }
            $array['type'] = 2;
            Systemlog::write($array);
        }
        return $next($request);
    }
}
